import requests
from tkinter import *
import re
import sqlite3

def ClientSQL():#创建并测试数据库
    try :
        with sqlite3.connect("题库.db") as conn:
            c = conn.cursor()
            b = c.execute("select * from TIKU")
            return
    except:
        with sqlite3.connect("题库.db") as conn:
            c = conn.cursor()
            c.execute('''CREATE TABLE TIKU
        (QUESTION           TEXT    NOT NULL,
        ANSWER            TEXT     NOT NULL);
        ''')
        return

class SQL(object):
    def __init__(self,question):
        ClientSQL()#先测试数据库
        self.SqlClient = sqlite3.connect("题库.db")
        self.question = re.sub("【.*?】","",question)
        print(self.question)
        self.headers = {
            "User-Agent":"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
            'Content-type': 'application/x-www-form-urlencoded',
            'Authorization': 'undefined',
        }

        self.data = {
            'question':self.question,
            'type':'0',
        }

    def query(self):
        cli = self.SqlClient.cursor()
        data = cli.execute(f"SELECT QUESTION='{self.question}',ANSWER FROM TIKU")
        answer = data.fetchall()
        cli.close()
        print(answer)

        return answer

    def Get_Answer(self):
        try :
            res = requests.post(url = "http://cx.icodef.com/wyn-nb?v=2",headers = self.headers,data = self.data)
            res.raise_for_status()
            answer = res.json()['data']
            self.save_data(answer)
        except:
            answer = None
            print("出现异常！")
        return answer

    def save_data(self,data):
        cli = self.SqlClient.cursor()
        print(f"INSERT INTO TIKU (QUESTION,ANSWER) VALUES ('{self.question}','{data}');")
        try:
            cli.execute(f"INSERT INTO TIKU(QUESTION ,ANSWER) VALUES (\"{self.question}\", \"{data}\"); ")
            self.SqlClient.commit()
            cli.close()
            print("写入数据库成功！")
        except:
            print("写入数据库异常！")
        return None

    def main(self):
        data = self.query()
        answer = data
        sql = set()
        for i in data:
            sql.add(i[0])
        print(sql)
        if sql == {} or sql == {0}:
            answer = self.Get_Answer()
            return answer
        else:
            return dict(answer)[1]

    def __enter__(self):#和__exit__ 配合可以使用with功能
        return self.main()

    def __exit__(self, exceptionType, exceptionVal, trace):
        print('exit')
        self.SqlClient.close()


class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name

    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("超星答案查询")           #窗口名
        self.init_window_name.geometry('800x520+10+10')                         #290 160为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        #标签
        self.init_data_label = Label(self.init_window_name, text="题目",font='Arial 15')
        self.init_data_label.grid(row=0, column=0)
        self.result_data_label = Label(self.init_window_name, text="答案",font='Arial 15')
        self.result_data_label.grid(row=0, column=12)
        #文本框
        self.init_data_Text = Text(self.init_window_name, width=30, height=20,font='Arial 15')  #原始数据录入框
        self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
        self.result_data_Text = Text(self.init_window_name, width=30, height=20,font='Arial 15')  #处理结果展示
        self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
        #按钮
        self.soushuo = Button(self.init_window_name, text="搜索", bg="lightblue",font='Arial 15',width=10,height=5,command=self.Get_Answer)  # 调用内部方法  加()为直接调用
        self.soushuo.grid(row=1, column=11)


    def Get_Answer(self):
        question = self.init_data_Text.get(1.0,END).strip().replace("\n","")
        print(question)
        try:
            # print("进入try1")
            with SQL(question) as f:
                print("进入SQL")
                a = f
            print("出来SQL")
            try:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,a.replace('#','\n'))
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"出现异常！\n请重试！")
        except:
            self.result_data_Text.delete(1.0,END)
            self.result_data_Text.insert(1.0,"网络出现异常(或题库出现异常)！\n请重试！")

def gui_start():
    init_window = Tk()              #实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()          #父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示

if __name__ == '__main__':
    gui_start()
